package com.googlecode.wheres_my_stuff_okay_potato;

import static android.widget.Toast.LENGTH_LONG;
import static android.widget.Toast.makeText;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final Global GLOBAL = (Global) getApplication();

		final EditText usernameET = (EditText) findViewById(R.id.username_et);
		final EditText passwordET = (EditText) findViewById(R.id.password_et);

		findViewById(R.id.login_b).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String username = usernameET.getText().toString();

				try {
					GLOBAL.attemptLogin(username, passwordET.getText()
							.toString());
					// makeText(getApplicationContext(),
					// R.string.login_successful_toast, LENGTH_LONG).show();
					Intent i = new Intent(MainActivity.this
							.getApplicationContext(), DashboardActivity.class);
					startActivity(i);
					finish();
				} catch (User.WrongPasswordException wpe) {
					makeText(getApplicationContext(),
							R.string.wrong_password_toast, LENGTH_LONG).show();
					passwordET.setText("");
				} catch (User.LockedException le) {
					makeText(getApplicationContext(), R.string.locked_toast,
							LENGTH_LONG).show();
					usernameET.setText("");
					passwordET.setText("");
					getWindow().getDecorView().setBackgroundColor(Color.RED);
				} catch (LoginHandler.UserNotFoundException unfe) {
					makeText(getApplicationContext(),
							R.string.user_not_found_toast, LENGTH_LONG).show();
				}
			}
		});

		findViewById(R.id.register_b).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(
						MainActivity.this.getApplicationContext(),
						RegisterActivity.class);
				i.putExtra("username", usernameET.getText().toString());
				startActivity(i);
				finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}